package com.sy.muldatasource.config;

import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

@Configuration  //定义主配置类，在启动时注入bean到spring容器中
@EnableJpaRepositories( //用来扫描指定的包及其子包中repository定义
        entityManagerFactoryRef="entityManagerFactoryTwo", 
        basePackages= { "com.sy.muldatasource.dao.two" }
        		)//设置dao层（持久层，即repo）所在位置
public class DataSourceConfigTwo {

    @Resource
    @Qualifier("dataSourceTwo")
    private DataSource dataSourceTwo; //注入主配置类中的主数据源


    @Bean(name = "entityManagerFactoryTwo")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabase(Database.MYSQL);
        vendorAdapter.setShowSql(true);
        
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("com.sy.muldatasource.pojo.two"); //设置实体类包所在位置
        factory.setJtaDataSource(dataSourceTwo); //指定数据源
        factory.setPersistenceUnitName("2");
        
        return factory;
    }
    

}
